package ch.abcm.remsmobile.REMSMobile.preferences;

import java.util.List;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import ch.abcm.remsmobile.REMSMobile.R;
import ch.abcm.remsmobile.REMSMobile.externnotifier.ExternNotifierController;
import ch.abcm.remsmobile.REMSMobile.orm.DatabaseOpenHelper;
import ch.abcm.remsmobile.REMSMobile.orm.model.Treshhold;

public class PrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

	public static final String KEY_PREFRENCES_PERIODIC_NOTIFICATION_TIMEOUT = "PeriodicNotifications";
	public static final String KEY_PREFRENCES_MEASUREMENT_DIVERGENCE_TIMEOUT = "MeasurementDivergence";
	public static final String KEY_PREFRENCES_SYSTEM_ERROR_TIMEOUT = "SystemError";
	public static final String KEY_PREFRENCES_RECEPIENT = "Recipient";
	public static final String KEY_PREFRENCES_NETWORK = "Network";
	public static final String KEY_PREFRENCES_NOTIFICATION_TYPE = "Notifications";

	public static final String DEFAULT_TIMEOUT_IN_SECONDS = "10";
	private static final String TAG = "PrefsActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPrefsFragment()).commit();
		PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
	}

	private static class MyPrefsFragment extends PreferenceFragment {

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.prefs);
		}
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		String newValue = sharedPreferences.getString(key, "unknown");
		String text = getString(R.string.changedPrefs);
		String message= text+" "+key+": "+newValue;
		Intent intent = ExternNotifierController.getSimpleMessageIntent(message);
		Log.d(TAG, message);
		sendBroadcast(intent);
		Log.i(TAG, "Prefs has changed, > deleting all tresholds");
		deletingallTreshholds();
	}

	private void deletingallTreshholds() {
		DatabaseOpenHelper databaseHelper = OpenHelperManager.getHelper(this, DatabaseOpenHelper.class);
		try {
			RuntimeExceptionDao<Treshhold, Integer> dao = databaseHelper.getTreshholdRuntimeExDao();
			List<Treshhold> queryForAll = dao.queryForAll();
			for (Treshhold treshhold : queryForAll) {
				dao.delete(treshhold);
			}
		} catch (Exception e) {
			Log.e(TAG, "deleting failed", e);
		}
	}
}
